package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单任务类
 */

@Component
@Slf4j
public class OrderTask {
    @Autowired
    OrdersMapper ordersMapper;

    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder(){
        //1.获取当前时间
        //2.当前时间减15分钟
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        //3.根据待支付状态和时间去数据库查询超时的订单
        List<Orders> orders = ordersMapper.findTimeoutOrders(Orders.PENDING_PAYMENT,time);
        //4.变量将订单的状态改成已取消
        if (orders != null && orders.size()>0) {
            orders.forEach(
                    order ->{
                        order.setStatus(Orders.CANCELLED);
                        order.setCancelReason("支付超时,自动取消");
                        order.setCancelTime(LocalDateTime.now());
                        ordersMapper.update(order);
                    }
            );
        }
    }
}
